﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

using NI.Common;

using NI.Winter;
using NReco.Winter;
using NReco.Converting;

namespace Wateco.Core {
	public static class ConfigManager {
		private static INamedServiceProvider ServiceProvider;

		public static void Configure() {
			Configure(null);
		}

		public static void Configure(string sectionName) {
			var config = CreateConfig(sectionName);
			ServiceProvider = new NReco.Winter.ServiceProvider(config);
		}

		private static IComponentsConfig CreateConfig(string sectionName) {
			return ConfigurationManager.GetSection(sectionName ?? "components") as IComponentsConfig;
		}

		public static object GetService(string serviceName) {
			object service = ServiceProvider.GetService(serviceName);
			/*if (service == null)
				log.Write(LogEvent.Warn, "Service with name '{0}' not found.", serviceName);*/
			return service;
		}

		public static object GetService(string serviceName, Type t) {
			object service = GetService(serviceName);
			return t.IsInstanceOfType(service) ? service : ConvertManager.ChangeType(service, t);
		}

		public static T GetService<T>(string serviceName) {
			return (T)GetService(serviceName, typeof(T));
		}

		public static object GetService(Type serviceType) {
			return (ServiceProvider as IServiceProvider).GetService(serviceType);
		}

		public static T GetService<T>() {
			return (T)GetService(typeof(T));
		}
	}
}
